#pragma once
#include <iostream>
#include <pthread.h>
#include <functional>
#include "Socket.hpp"
// 对于将要连接的进程，创建相应的线程进行处理
using namespace std;
using func_t = function<string(string &, bool *error_cpde)>;
class TcpServer;
class ThreadData
{
public:
    ThreadData(TcpServer *tcp_this, Socket *sockp)
        : _this(tcp_this), _sockp(sockp)
    {
    }

    TcpServer *_this;
    Socket *_sockp;
};

// 梳理一下逻辑，写一个自己的p2p
class TcpServer
{
public:
    TcpServer(uint16_t port)
        : _port(port), _listensocket(new TcpSocket()) // 新建立一个套接字
    {
        _listensocket->BuildListenSocketMethod(_port, backlog);
    }
    static void *ThreadRun(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args); // 这个的原理?
        string inbufferstream;
        while (true)
        {
            bool ok = true;
            td->_sockp->Recv(&inbufferstream, 1024);
            string re = "bye";
            if (inbufferstream == "wakuwaku")
            {
                re="go out";
            }
            cout << "接收到：" << inbufferstream << endl;
            if (inbufferstream.size() == 0)
            {
                break;
            }
            inbufferstream.clear();
            // 返回消息
            td->_sockp->Send(re);
            if(re=="go out")
            {
                break;
            }
        }
        td->_sockp->CloseSocket();//不能到这里
        delete td->_sockp;
        delete td;
        return nullptr;
    }
    void Loop() // 这个函数是创建线程完成任务的
    {
        while (true)
        {
            string peerip;
            uint16_t peerport;
            Socket *newsock = _listensocket->AcceptConnection(&peerip, &peerport); // 开始时就直接new了一个套接字,这个函数是输出型参数
            if (newsock == nullptr)
            {
                continue;
            }
            cout << "获取了一个新链接，sockfd:" << newsock->GetSockFd() << "client info" << peerip << ":" << "peerport" << endl;
            pthread_t tid;
            ThreadData *td = new ThreadData(this, newsock);
            pthread_create(&tid, nullptr, ThreadRun, td);
            // 这个线程已经不会回来了。
        }
    }
    ~TcpServer() {}

private:
    int _port;
    Socket *_listensocket;
};
